<template>
    <div class="editor-v2-page">
        <PageHeader height="50vh" :customTexts="['创作中心 | 记录你的优质博客', '将灵感变为篇章，记录此刻的想法', '始于代码，不止于代码。']"
            :imageSourcesConfig="['fj']" :backgroundChangeInterval="30000" :overlay="true" :overlayOpacity="0.4"
            :showBackgroundSwitch="false" />

        <div class="editor-v2-main">
            <el-form :model="articleForm" :rules="rules" ref="articleForm" label-position="top" class="editor-layout"
                :class="{ 'fullscreen-mode': isEditorFullscreen }">
                <!-- 主要内容区 -->
                <div class="editor-content-area">
                    <!-- 基础信息：标题、描述、封面 -->
                    <div class="content-card">
                        <div class="title-cover-grid">
                            <div class="title-section">
                                <el-form-item label="文章标题" prop="title">
                                    <el-input v-model="articleForm.title" placeholder="请输入文章标题..." />
                                </el-form-item>
                                <el-form-item label="文章描述" prop="summary">
                                    <el-input v-model="articleForm.summary" type="textarea" :rows="4"
                                        placeholder="请输入文章描述..." />
                                </el-form-item>
                            </div>
                            <div class="cover-section">
                                <el-form-item label="封面图片" prop="cover">
                                    <div class="cover-uploader" @click="triggerCoverUpload">
                                        <div v-if="!articleForm.cover" class="cover-placeholder">
                                            <i class="fas fa-image"></i>
                                            <span>点击上传封面</span>
                                        </div>
                                        <div v-else class="cover-preview">
                                            <img :src="articleForm.cover" alt="文章封面" />
                                            <div class="cover-actions">
                                                <el-button size="mini" circle icon="el-icon-view"
                                                    @click.stop="previewCoverImage" />
                                                <el-button size="mini" circle icon="el-icon-delete" type="danger"
                                                    @click.stop="removeCover" />
                                            </div>
                                        </div>
                                    </div>
                                    <input ref="coverInput" type="file" accept="image/*" @change="handleCoverUpload"
                                        style="display: none" />
                                </el-form-item>
                            </div>
                        </div>
                    </div>

                    <!-- 编辑器区域 -->
                    <div class="content-card editor-sticky-container">
                        <div class="editor-area">
                            <div class="editor-toolbar">
                                <div class="editor-switcher">
                                    <el-radio-group v-model="editorType" size="small">
                                        <el-radio-button label="markdown">
                                            <i class="fab fa-markdown"></i> Markdown
                                        </el-radio-button>
                                        <el-radio-button label="richtext" v-if="!isMobile">
                                            <i class="fas fa-magic"></i> 富文本
                                        </el-radio-button>
                                    </el-radio-group>
                                </div>
                                <div class="markdown-tools">
                                    <el-tooltip effect="dark" content="下载Markdown模板" placement="top">
                                        <el-button size="mini" @click="downloadMarkdownTemplate"
                                            icon="el-icon-download">
                                            模板
                                        </el-button>
                                    </el-tooltip>
                                    <el-tooltip effect="dark" content="导入Markdown文件" placement="top">
                                        <el-button size="mini" @click="triggerMarkdownUpload" icon="el-icon-upload2">
                                            导入
                                        </el-button>
                                    </el-tooltip>
                                    <el-tooltip effect="dark" content="清空所有内容" placement="top">
                                        <el-button size="mini" @click="confirmClearContent" icon="el-icon-delete">
                                            清空
                                        </el-button>
                                    </el-tooltip>
                                    <el-tooltip effect="dark" content="预览文章" placement="top">
                                        <el-button size="mini" @click="showPreview" icon="el-icon-view" plain>
                                            预览
                                        </el-button>
                                    </el-tooltip>
                                    <input ref="markdownInput" type="file" accept=".md" @change="handleMarkdownUpload"
                                        style="display: none" />
                                </div>
                            </div>

                            <el-form-item v-if="editorType === 'markdown'" prop="contentMd" class="editor-form-item">
                                <div class="editor-wrapper markdown-editor-wrapper"
                                    :class="{ 'is-fullscreen': isEditorFullscreen }">
                                    <mavon-editor placeholder="输入文章内容..." style="height: 100%; width: 100%" ref="mdRef"
                                        v-model="articleForm.contentMd" @imgDel="imgDel" @imgAdd="imgAdd"
                                        @fullScreen="handleFullScreen" :default-open="'edit'" />
                                </div>
                            </el-form-item>

                            <el-form-item v-if="editorType === 'richtext'" prop="content" class="editor-form-item">
                                <div class="editor-wrapper richtext-editor-wrapper"
                                    :class="{ 'is-fullscreen': isEditorFullscreen }">
                                    <UEditorPlus v-model="articleForm.content" @fullscreen-change="handleFullScreen" />
                                </div>
                            </el-form-item>
                        </div>
                    </div>
                </div>

                <!-- 侧边栏 -->
                <div class="editor-sidebar-area">
                    <div class="sidebar-card">
                        <h3 class="sidebar-title"><i class="fas fa-folder"></i> 文章分类</h3>
                        <el-form-item prop="categoryId">
                            <el-select v-model="articleForm.categoryId" placeholder="请选择分类" style="width: 100%">
                                <el-option v-for="item in categories" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </div>

                    <div class="sidebar-card">
                        <h3 class="sidebar-title"><i class="fas fa-tags"></i> 文章标签</h3>
                        <el-form-item prop="tagIds">
                            <el-select v-model="articleForm.tagIds" multiple filterable placeholder="请选择标签"
                                style="width: 100%">
                                <el-option v-for="item in tags" :key="item.id" :label="item.name" :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </div>

                    <div class="sidebar-card">
                        <h3 class="sidebar-title"><i class="fas fa-cog"></i> 文章设置</h3>
                        <el-form-item label="文章来源">
                            <el-switch v-model="articleForm.isOriginal" :active-value="1" :inactive-value="0"
                                active-text="原创" inactive-text="转载" />
                        </el-form-item>
                        <el-form-item v-if="!articleForm.isOriginal" prop="originalUrl">
                            <el-input v-model="articleForm.originalUrl" placeholder="请输入原文地址" />
                        </el-form-item>
                        <el-form-item label="关键词" prop="keywords">
                            <el-input v-model="articleForm.keywords" placeholder="多个用逗号隔开" />
                        </el-form-item>
                        <el-form-item label="阅读模式" prop="readType">
                            <el-select v-model="articleForm.readType" placeholder="请选择" style="width: 100%">
                                <el-option v-for="item in readTypeOptions" :key="item.value" :label="item.label"
                                    :value="item.value">
                                    <i :class="item.icon" style="margin-right: 8px;"></i>
                                    <span>{{ item.label }}</span>
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </div>

                    <div class="sidebar-card sticky-card">
                        <div class="action-buttons">
                            <el-button @click="saveDraft" icon="el-icon-document">保存草稿</el-button>
                            <el-button type="primary" @click="publishArticle" icon="el-icon-position">
                                {{ articleForm.status === 1 ? '更新文章' : '发布文章' }}
                            </el-button>
                        </div>
                        <el-alert :title="articleForm.status === 1 ? '提示：更新后将对访问者可见' : '提示：发布后将公开可见'" type="info"
                            :closable="false" show-icon />
                    </div>
                </div>
            </el-form>
        </div>
        <mj-image-preview ref="imagePreview" />

        <!-- 文章预览弹窗 -->
        <el-dialog :visible.sync="previewVisible" custom-class="preview-dialog" fullscreen
            :before-close="handleClosePreview" @opened="onPreviewDialogOpened">
            <div class="preview-container">
                <ArticlePreview ref="articlePreviewRef" v-if="previewVisible" :preview-data="previewArticleData"
                    :is-preview-mode="true" />
            </div>
            <div class="preview-close-btn" @click="handleClosePreview">
                <i class="el-icon-close"></i>
            </div>
        </el-dialog>
    </div>
</template>

<script>
// 重构之前编辑器里的排版后的实现 <script>内容和原文件保持一致...
import { uploadFileApi, deleteFileApi, importMarkdownApi, downloadMarkdownTemplateApi } from '@/api/file'
import { createArticleApi, updateArticleApi, getArticleInfoApi } from '@/api/article'
import { getTagsApi, getCategoriesApi } from '@/api/tags'
import { getDictDataApi } from '@/api/dict'
import PageHeader from '@/components/PageHeader/index.vue'
import UEditorPlus from '@/components/UEditorPlus/index.vue'
import ArticlePreview from '@/views/article/index.vue'
import markdownit from 'markdown-it'
import TurndownService from 'turndown'

export default {
    name: 'Editor',
    components: {
        PageHeader,
        UEditorPlus,
        ArticlePreview
    },
    data() {
        return {
            articleForm: {
                title: '',
                summary: '',
                content: '',
                contentMd: '',
                cover: '',
                keywords: '',
                isOriginal: 1,
                originalUrl: '',
                categoryId: '',
                tagIds: [],
                status: '',
                readType: 0, // 0: 公开, 1: 评论, 2: 点赞, 3: 评论+点赞
                updateTime: null
            },
            rules: {
                title: [
                    { required: true, message: '请输入文章标题', trigger: 'blur' },
                    { min: 5, max: 100, message: '标题长度应在5-100个字符之间', trigger: 'blur' }
                ],
                summary: [
                    { required: true, message: '请输入文章描述', trigger: 'blur' },
                    { min: 10, max: 500, message: '描述长度应在10-500个字符之间', trigger: 'blur' }
                ],
                contentMd: [
                    {
                        validator: (rule, value, callback) => {
                            if (this.editorType !== 'markdown') {
                                return callback();
                            }
                            if (!value) {
                                callback(new Error('请输入文章内容'));
                                return;
                            }

                            // 检查最小长度
                            if (value.length < 50) {
                                callback(new Error('文章内容至少需要50个字符'));
                                return;
                            }

                            // 检查重复字符
                            const repeatedCharPattern = /(.)\1{4,}/;

                            // 检查内容是否有意义
                            const meaninglessPattern = /^[a-zA-Z]{10,}$/;
                            if (meaninglessPattern.test(value)) {
                                callback(new Error('文章内容似乎没有实际意义，请认真编写'));
                                return;
                            }


                            callback();
                        },
                        trigger: ['blur', 'change']
                    }
                ],
                content: [
                    {
                        validator: (rule, value, callback) => {
                            if (this.editorType !== 'richtext') {
                                return callback();
                            }
                            // UEditor might return this for an empty editor
                            if (!value || value === '<p><br></p>' || value.length < 50) {
                                callback(new Error('文章内容至少需要50个字符'));
                            } else {
                                callback();
                            }
                        },
                        trigger: ['blur', 'change']
                    }
                ],
                cover: [
                    { required: true, message: '请上传封面图片', trigger: 'change' }
                ],
                categoryId: [
                    { required: true, message: '请选择文章分类', trigger: 'change' }
                ],
                tagIds: [
                    { required: true, message: '请选择文章标签', trigger: 'change' },
                    {
                        validator: (rule, value, callback) => {
                            if (value.length > 3) {
                                callback(new Error('最多只能选择3个标签'));
                            } else {
                                callback();
                            }
                        },
                        trigger: 'change'
                    }
                ],
                originalUrl: [
                    { required: true, message: '请输入原文地址', trigger: 'blur' },
                    { type: 'url', message: '请输入有效的URL地址', trigger: 'blur' }
                ],
                keywords: [
                    {
                        validator: (rule, value, callback) => {
                            if (value && value.split(',').length > 5) {
                                callback(new Error('关键词最多不超过5个'));
                            } else {
                                callback();
                            }
                        },
                        trigger: 'blur'
                    }
                ]
            },
            categories: [],
            tags: [],
            isSubmitting: false,
            statusList: [],
            readTypeOptions: [
                { value: 0, label: '公开阅读', icon: 'fas fa-globe-asia' },
                { value: 1, label: '评论后阅读', icon: 'fas fa-comment-dots' },
                { value: 2, label: '点赞后阅读', icon: 'fas fa-thumbs-up' },
                { value: 3, label: '评论并点赞后阅读', icon: 'fas fa-user-lock' }
            ],
            isEditorFullscreen: false,
            editorType: 'markdown', // markdown or richtext
            isMobile: false,
            previewVisible: false,
            previewArticleData: null
        }
    },
    mounted() {
        this.checkIsMobile();
        window.addEventListener('resize', this.checkIsMobile);
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.checkIsMobile);
    },
    created() {
        const urlEditorType = this.$route.query.editor_type;
        const preferredEditorType = localStorage.getItem('preferred-editor-type');
        let editorDetermined = false;

        // 优先使用URL中的编辑器类型
        if (urlEditorType && (urlEditorType === 'markdown' || urlEditorType === 'richtext')) {
            if (!(window.innerWidth <= 768 && urlEditorType === 'richtext')) {
                this.editorType = urlEditorType;
                editorDetermined = true;
            }
        }
        // 其次使用localStorage中的偏好设置
        else if (preferredEditorType && (preferredEditorType === 'markdown' || preferredEditorType === 'richtext')) {
            if (!(window.innerWidth <= 768 && preferredEditorType === 'richtext')) {
                this.editorType = preferredEditorType;
                editorDetermined = true;
            }
        }

        this.articleForm.id = this.$route.query.id;

        // 定义需要预先加载的主数据请求
        const masterDataPromises = [
            getCategoriesApi(),
            getTagsApi()
        ];

        // 字典数据可以独立加载
        getDictDataApi(['article_status']).then(res => {
            this.statusList = res.data;
        });

        // 等待所有主数据加载完成后再处理文章详情
        Promise.all(masterDataPromises).then(([categoriesRes, tagsRes]) => {
            this.categories = categoriesRes.data;
            this.tags = tagsRes.data;

            // 如果是编辑模式，现在获取文章详情
            if (this.articleForm.id) {
                getArticleInfoApi(this.articleForm.id).then(res => {
                    const articleData = res.data;

                    // 根据内容判断编辑器类型（如果尚未确定）
                    if (!editorDetermined) {
                        if (articleData.contentMd && articleData.contentMd.length > 0) {
                            this.editorType = 'markdown';
                        } else if (articleData.content && articleData.content.length > 0) {
                            this.editorType = 'richtext';
                        }
                    }

                    // 健壮性处理：确保 tagIds 存在，以正确绑定 v-model
                    // 如果API因某些原因未返回 tagIds，则从 tags 对象数组中生成它
                    if ((!articleData.tagIds || articleData.tagIds.length === 0) &&
                        articleData.tags && Array.isArray(articleData.tags) && articleData.tags.length > 0) {
                        articleData.tagIds = articleData.tags.map(tag => tag.id);
                    }

                    // 将获取到的数据赋值给表单
                    this.articleForm = articleData;
                });
            }
        });
    },
    methods: {
        checkIsMobile() {
            const mobile = window.innerWidth <= 768;
            // Only act on change
            if (mobile !== this.isMobile) {
                this.isMobile = mobile;
                if (this.isMobile && this.editorType === 'richtext') {
                    this.editorType = 'markdown';
                    this.$message.warning({
                        message: '富文本编辑器不适用移动端，已切换至Markdown。如需编辑原文，请使用桌面设备。',
                        duration: 5000,
                        showClose: true,
                    });
                }
            }
        },
        /**
         * 处理编辑器全屏状态变化 (统一处理)
         */
        handleFullScreen(status) {
            this.isEditorFullscreen = status;
        },
        /**
         * 保存草稿
         */
        async saveDraft() {
            // 设置为草稿状态(2)
            this.articleForm.status = 2;
            this.submitArticle(false); // 传入false表示不进行严格校验
        },
        /**
         * 预览文章
         */
        showPreview() {
            this.$refs.articleForm.validate((valid) => {
                if (!valid) {
                    this.$message.warning('请先填写必填项再预览');
                    return;
                }

                if (this.editorType === 'markdown') {
                    this.articleForm.content = this.$refs.mdRef.d_render;
                } else {
                    const turndownService = new TurndownService();
                    this.articleForm.contentMd = turndownService.turndown(this.articleForm.content);
                }

                // 准备预览数据
                const category = this.categories.find(c => c.id === this.articleForm.categoryId);
                const tags = this.tags.filter(t => this.articleForm.tagIds.includes(t.id));

                this.previewArticleData = {
                    ...this.articleForm,
                    nickname: this.$store.state.userInfo ? this.$store.state.userInfo.nickname : '测试用户',
                    avatar: this.$store.state.userInfo ? this.$store.state.userInfo.avatar : '',
                    createTime: new Date().toLocaleString(),
                    updateTime: new Date().toLocaleString(),
                    quantity: 0,
                    commentNum: 0,
                    likeNum: 0,
                    favoriteNum: 0,
                    isLike: false,
                    isFavorite: false,
                    isCommented: false,
                    draftMode: false,
                    fullContent: true,
                    category: category || { name: '未分类' },
                    tags: tags || [],
                };
                this.previewVisible = true;
            });
        },
        /**
         * 预览弹窗完全打开后的回调
         */
        onPreviewDialogOpened() {
            if (this.$refs.articlePreviewRef) {
                this.$refs.articlePreviewRef.triggerInitialization();
            }
        },
        /**
         * 关闭预览
         */
        handleClosePreview() {
            this.previewVisible = false;
            this.previewArticleData = null;
        },
        /**
         * 发布文章
         */
        async publishArticle() {
            // 设置为发布状态(1)
            this.articleForm.status = 1;
            this.submitArticle(true); // 传入true表示进行严格校验
        },
        /**
         * 提交文章
         * @param {boolean} strictValidate 是否进行严格验证
         */
        submitArticle(strictValidate = true) {
            // 保存用户偏好的编辑器类型
            localStorage.setItem('preferred-editor-type', this.editorType);

            if (this.isSubmitting) return;

            // 根据编辑器类型处理内容
            if (this.editorType === 'markdown') {
                // 获取Markdown渲染的HTML内容
                this.articleForm.content = this.$refs.mdRef.d_render;
            } else {
                // 如果是富文本编辑器，将HTML内容转为Markdown
                const turndownService = new TurndownService()
                this.articleForm.contentMd = turndownService.turndown(this.articleForm.content)
            }

            // 当使用富文本编辑器时，`content` 已经通过 `v-model` 绑定。
            // 我们不会清除 `contentMd`，以防它是从导入的 Markdown 文件中获得的。

            // 草稿状态时只进行基本验证
            if (!strictValidate) {
                // 草稿状态只验证标题，允许其他字段为空
                if (!this.articleForm.title) {
                    this.$message.warning('请至少输入文章标题');
                    return;
                }

                // 设置默认值防止提交失败
                if (!this.articleForm.summary) {
                    this.articleForm.summary = this.articleForm.title.substring(0, 100);
                }

                this.isSubmitting = true;

                const api = this.articleForm.id ? updateArticleApi : createArticleApi;

                api(this.articleForm)
                    .then(res => {
                        this.$message.success('草稿保存成功');
                        this.$router.push('/user/profile');
                    })
                    .catch(err => {
                        console.error('保存草稿失败:', err);
                        this.$message.error(err.message || '保存失败，请稍后重试');
                    })
                    .finally(() => {
                        this.isSubmitting = false;
                    });

                return;
            }

            // 正常发布时进行完整验证
            this.$refs.articleForm.validate(valid => {
                if (!valid) {
                    this.$message.warning('表单验证失败，请检查填写的内容');
                    return;
                }

                this.isSubmitting = true;

                const api = this.articleForm.id ? updateArticleApi : createArticleApi;
                const successMessage = this.articleForm.id ? '文章更新成功' : '文章发布成功';
                const errorMessage = this.articleForm.id ? '更新失败，请稍后重试' : '发布失败，请稍后重试';

                api(this.articleForm)
                    .then(res => {
                        this.$message.success(successMessage);
                        this.$router.push('/user/profile');
                    })
                    .catch(err => {
                        console.error('提交文章失败:', err);
                        this.$message.error(err.message || errorMessage);
                    })
                    .finally(() => {
                        this.isSubmitting = false;
                    });
            });
        },
        /**
         * 删除图片
         */
        imgDel(pos, $file) {
            console.log(pos)
            deleteFileApi(pos[0]).then(res => {
                this.$refs.mdRef.$img2Url(pos, '');
            });
        },
        /**
         * 添加图片
         */
        imgAdd(pos, $file) {
            const formdata = new FormData();
            formdata.append("file", $file);
            uploadFileApi(formdata, 'article-content').then(res => {
                this.$refs.mdRef.$img2Url(pos, res.data);
            });
        },
        /**
         * 触发封面上传
         */
        triggerCoverUpload() {
            this.$refs.coverInput.click()
        },
        /**
         * 封面上传
         */
        handleCoverUpload(e) {
            const file = e.target.files[0]
            if (!file) return

            const formData = new FormData()
            formData.append('file', file)

            uploadFileApi(formData, 'article-cover').then(res => {
                if (res.code === 200) {
                    this.articleForm.cover = res.data
                    this.$message.success('上传成功')
                } else {
                    this.$message.error(res.message || '上传失败')
                }
            }).catch(error => {
                this.$message.error('上传失败，请重试')
            })

            // 清空 input 的值，这样可以重复上传同一个文件
            e.target.value = ''
        },
        /**
         * 删除封面
         */
        removeCover() {
            this.articleForm.cover = ''
        },
        /**
         * 下载Markdown模板
         */
        downloadMarkdownTemplate() {
            this.$message.info('正在准备下载...');
            downloadMarkdownTemplateApi().then(response => {
                // response.data 现在是 blob 对象
                const blob = new Blob([response.data], { type: 'text/markdown;charset=utf-8' });

                // 从响应头中获取文件名
                const contentDisposition = response.headers['content-disposition'];
                let fileName = 'Markdown模板文件-article.md'; // 默认文件名
                if (contentDisposition) {
                    const fileNameMatch = contentDisposition.match(/filename="?([^"]+)"?/);
                    if (fileNameMatch && fileNameMatch.length > 1) {
                        fileName = decodeURIComponent(fileNameMatch[1]);
                        // 文件名已经包含时间戳，不需要再添加
                        const link = document.createElement('a');
                        link.href = window.URL.createObjectURL(blob);
                        link.download = fileName;
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                        window.URL.revokeObjectURL(link.href);
                        this.$message.success('模板已开始下载');
                        return;
                    }
                }

                // 如果没有从响应头获取到文件名，则使用默认文件名并添加时间戳
                const timestamp = new Date().getTime();
                const fileNameParts = fileName.split('.');
                const extension = fileNameParts.pop();
                const nameWithoutExt = fileNameParts.join('.');
                const uniqueFileName = `${nameWithoutExt}-${timestamp}.${extension}`;

                const link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = uniqueFileName;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                window.URL.revokeObjectURL(link.href);
                this.$message.success('模板已开始下载');
            }).catch(error => {
                console.error('下载模板失败:', error);
                this.$message.error('下载模板失败，请检查网络或联系管理员');
            });
        },
        /**
         * 触发Markdown文件上传
         */
        triggerMarkdownUpload() {
            this.$refs.markdownInput.click();
        },
        /**
         * 处理Markdown文件上传
         */
        handleMarkdownUpload(e) {
            const file = e.target.files[0];
            if (!file) return;

            // 创建FormData对象
            const formData = new FormData();
            formData.append('file', file);

            this.$message.info('正在解析Markdown文档...');

            // 调用导入API
            importMarkdownApi(formData).then(res => {
                if (res.code === 200) {
                    const data = res.data;

                    // 填充表单数据
                    this.articleForm.title = data.title || this.articleForm.title;
                    this.articleForm.summary = data.summary || this.articleForm.summary;
                    this.articleForm.contentMd = data.contentMd || this.articleForm.contentMd;
                    this.articleForm.keywords = data.keywords || this.articleForm.keywords;
                    this.articleForm.isOriginal = data.isOriginal !== undefined ? data.isOriginal : this.articleForm.isOriginal;
                    this.articleForm.originalUrl = data.originalUrl || this.articleForm.originalUrl;

                    if (data.cover) {
                        this.articleForm.cover = data.cover;
                    }

                    // 根据当前编辑器类型，更新对应的内容
                    if (this.editorType === 'richtext') {
                        const md = markdownit();
                        this.articleForm.content = md.render(this.articleForm.contentMd);
                    } else {
                        // 导入后，同步更新富文本编辑器的内容
                        this.$nextTick(() => {
                            if (this.$refs.mdRef && this.$refs.mdRef.d_render) {
                                this.articleForm.content = this.$refs.mdRef.d_render;
                            }
                        });
                    }

                    // 显示导入成功信息
                    this.$message.success(data.message || 'Markdown文档导入成功');

                    // 如果有警告信息，显示警告
                    if (data.warnings && data.warnings.length > 0) {
                        this.$notify({
                            title: '导入警告',
                            message: '导入过程中有一些问题需要注意，请查看详情',
                            type: 'warning',
                            duration: 10000,
                            showClose: true,
                            dangerouslyUseHTMLString: true,
                            onClose: function () { },
                            onClick: function () { }
                        });

                        data.warnings.forEach(function (warning) {
                            this.$notify.warning({
                                title: '导入警告',
                                message: warning,
                                duration: 10000,
                                showClose: true
                            });
                        }, this);
                    }
                } else {
                    this.$message.error(res.msg || '导入Markdown文档失败');
                }
            }).catch(error => {
                console.error('导入Markdown文档失败:', error);
                this.$message.error(error.message || '导入失败，请稍后重试');
            }).finally(() => {
                // 清空文件输入框，以便下次选择同一个文件时也能触发change事件
                e.target.value = '';
            });
        },
        /**
         * 确认清除所有内容
         */
        confirmClearContent() {
            this.$confirm('确定要清除所有内容吗？此操作不可恢复！', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            }).then(() => {
                this.clearAllContent();
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消清除操作'
                });
            });
        },

        /**
         * 清除所有内容
         */
        clearAllContent() {
            // 重置所有表单字段
            this.articleForm.title = '';
            this.articleForm.summary = '';
            this.articleForm.content = '';
            this.articleForm.contentMd = '';
            this.articleForm.cover = '';
            this.articleForm.keywords = '';
            this.articleForm.isOriginal = 1; // 保持默认值为原创
            this.articleForm.originalUrl = '';
            this.articleForm.categoryId = '';
            this.articleForm.tagIds = [];

            this.$nextTick(() => {
                // 重新渲染编辑器
                if (this.editorType === 'markdown' && this.$refs.mdRef) {
                    this.$refs.mdRef.d_render = '';
                }

                // 重置表单验证
                if (this.$refs.articleForm) {
                    this.$refs.articleForm.clearValidate();
                }
            });

            this.$message.success('所有内容已清除');
        },
        /**
         * 预览封面图片
         */
        previewCoverImage() {
            if (this.articleForm.cover) {
                this.$refs.imagePreview.show([this.articleForm.cover], 0);
            }
        }
    }
}
</script>

<style lang="scss" scoped>
// 基础变量与主题色
$primary-color: #4a90e2;

// 页面整体布局
.editor-v2-page {
    background-color: var(--page-bg);
}

.editor-v2-main {
    max-width: 1400px;
    margin: 0 auto;
    padding: 24px;
}

// 编辑器主布局（栅格）
.editor-layout {
    margin-top: -80px;
    position: relative;
    z-index: 10;
    display: grid;
    grid-template-columns: minmax(0, 1fr) 320px;
    gap: 24px;
    align-items: flex-start;
}

// 内容卡片通用样式
.content-card,
.sidebar-card {
    background: var(--card-bg);
    border-radius: 12px;
    padding: 24px;
    border: 1px solid var(--border-color);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
}

.editor-content-area {
    display: flex;
    flex-direction: column;
    gap: 24px;
}

// 标题与封面区域
.title-cover-grid {
    display: grid;
    grid-template-columns: minmax(0, 1fr) 240px;
    gap: 24px;
    align-items: flex-start;
}

.cover-uploader {
    width: 100%;
    height: 148px;
    border-radius: 8px;
    border: 2px dashed var(--border-color);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;

    &:hover {
        border-color: $primary-color;
        background-color: var(--hover-bg);
    }
}

.cover-placeholder {
    text-align: center;
    color: var(--text-secondary);

    i {
        font-size: 32px;
        margin-bottom: 8px;
    }
}

.cover-preview {
    width: 100%;
    height: 100%;
    position: relative;
    border-radius: 8px;
    overflow: hidden;

    img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .cover-actions {
        position: absolute;
        top: 8px;
        right: 8px;
        display: flex;
        gap: 8px;
        opacity: 0;
        transition: opacity 0.3s ease;
    }

    &:hover .cover-actions {
        opacity: 1;
    }
}

// 编辑器区域
.editor-area {
    display: flex;
    flex-direction: column;
}

.editor-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    flex-wrap: wrap;
    gap: 16px;
}

.markdown-tools {
    display: flex;
    gap: 8px;
}

.editor-form-item {
    margin-bottom: 0; // 移除 el-form-item 的默认 margin
}

.editor-wrapper {
    height: 600px;
    border: 1px solid var(--border-color);
    border-radius: 8px;
    overflow: hidden;

    :deep(.v-note-wrapper) {
        height: 100% !important;
        border: none !important;
    }
}

// 侧边栏
.editor-sidebar-area {
    display: flex;
    flex-direction: column;
    gap: 24px;
}

.sidebar-card {
    padding: 20px;
}

.sidebar-title {
    font-size: 16px;
    font-weight: 600;
    margin: 0 0 16px;
    display: flex;
    align-items: center;
    gap: 8px;

    i {
        color: $primary-color;
    }
}

.sticky-card {
    position: sticky;
    top: 80px;
}

.action-buttons {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    gap: 12px;
    margin-bottom: 16px;

    .el-button {
        width: 100%;
    }
}

// 全屏模式
.editor-layout.fullscreen-mode {
    .editor-content-area {
        // 在全屏模式下，让内容区占据整个栅格空间
        grid-column: 1 / -1;
    }

    .editor-sidebar-area {
        display: none;
    }
}

.editor-wrapper.is-fullscreen {
    position: fixed;
    left: 0;
    width: 100vw;
    z-index: 2000;
    border: none;
    border-radius: 0;
    background: var(--card-bg);

    &.markdown-editor-wrapper {
        top: 55px;
        height: calc(100vh - 55px);
    }

    :deep(.v-note-wrapper) {
        box-shadow: none !important;
    }
}

// mavon-editor 全屏样式覆盖
:deep(.v-note-wrapper.fullscreen) {
    top: 55px !important;
    height: calc(100vh - 55px) !important;
}

.editor-sticky-container {
    position: -webkit-sticky;
    position: sticky;
    top: 80px;
}

// Element UI 样式覆盖
:deep(.el-form-item__label) {
    padding-bottom: 8px;
    line-height: 1.5;
}

// 响应式设计
@media (max-width: 1024px) {
    .editor-layout {
        grid-template-columns: minmax(0, 1fr);
    }

    .sticky-card {
        position: static;
    }
}

@media (max-width: 768px) {
    .editor-v2-main {
        padding: 16px;
    }

    .editor-layout {
        margin-top: -60px;
    }

    .title-cover-grid {
        grid-template-columns: minmax(0, 1fr);
    }

    .cover-uploader {
        height: 180px;
    }

    .content-card,
    .sidebar-card {
        padding: 16px;
    }
}

.preview-dialog {
    background: transparent;
    box-shadow: none;

    .el-dialog__header {
        display: none;
    }

    .el-dialog__body {
        padding: 0;
        height: 100vh;
        background: transparent;
    }
}

.preview-container {
    height: 100%;
    overflow-y: auto;
    scrollbar-width: thin;
    scrollbar-color: #aaa #f1f1f1;
    border-radius: 12px;
    background: var(--page-bg);

    &::-webkit-scrollbar {
        width: 8px;
    }

    &::-webkit-scrollbar-track {
        background: #f1f1f1;
    }

    &::-webkit-scrollbar-thumb {
        background: #aaa;
        border-radius: 4px;
    }

    &::-webkit-scrollbar-thumb:hover {
        background: #888;
    }
}

.preview-close-btn {
    position: fixed;
    top: 20px;
    right: 40px;
    width: 40px;
    height: 40px;
    background: rgba(0, 0, 0, 0.3);
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    cursor: pointer;
    transition: all 0.3s ease;
    z-index: 2100;

    &:hover {
        background: rgba(0, 0, 0, 0.5);
        transform: rotate(90deg);
    }
}
</style>